package com.example.cgpsys.other.utils;


import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

public class FileUtils {

    public static String uploadImage(String path, MultipartFile file) throws IOException {
        File filePath = new File(path+"/avatar");
        if (!filePath.exists()){
            filePath.mkdirs();
        }

        String extension = getExtension(Objects.requireNonNull(file.getContentType()));

        if ("#".equals(extension)){
            return "#";
        }

        String newFileName=UUID.randomUUID().toString().replace("-","")+"."+extension;

        File targetFile = new File(filePath, newFileName);

        file.transferTo(targetFile);

        return "/profile/avatar/"+newFileName;
    }

    public static String getExtension(String prefix)
    {
        switch (prefix)
        {
            case "image/png":
                return "png";
            case "image/jpg":
                return "jpg";
            case "image/jpeg":
                return "jpeg";
            case "image/bmp":
                return "bmp";
            case "image/gif":
                return "gif";
            default:
                return "#";
        }
    }

}
